package test01.Exception;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import test01.Result.CodeMsg;
import test01.Result.Result;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static test01.Result.CodeMsg.SERVICE_ERROR;
import static test01.Result.CodeMsg.VALID_ERROR;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler{
    @ExceptionHandler(value=Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
        e.printStackTrace();
        if (e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e;
            List<ObjectError> errors = ex.getBindingResult().getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(VALID_ERROR.fillArgs(msg));
        }else if(e instanceof GlobalException){
            return Result.error(((GlobalException) e).getCm());
        }
        return Result.error(SERVICE_ERROR);
    }
}







